package com.darren.center.design.patterns.handler;

import com.darren.center.design.patterns.command.AbstractHandler;
import com.darren.center.design.patterns.dto.Context;
import com.darren.center.design.patterns.exceptions.ApiBizException;
import com.darren.center.design.patterns.utils.IpMatchUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <h3>design-patterns</h3>
 * <p>白名单过滤</p>
 *
 * @author : Darren
 * @date : 2021年06月14日 19:52:27
 **/
@Component
public class AuthHandler extends AbstractHandler {

    private static Logger logger = LoggerFactory.getLogger(AuthHandler.class);


    private static final String PARTNER_MATCH_REGEX = "<partnerId>([^<>]*)</partnerId>";

    public static final String IP_KEY = "oservice_auth_ip";

    private Pattern pattern = Pattern.compile(PARTNER_MATCH_REGEX);


    @Override
    public void processHandler(String reqXml, Context context) {
        String partnerId = getPartnerId(reqXml);
        if(StringUtils.isBlank(partnerId)){
            throw new ApiBizException(ApiBizException.VERIFY_IP_ERROR, "未知合作者");
        }
        String ip = context.getClientIP();
        String ipWhites = null;
        //校验
        if(IpMatchUtils.match(ip, ipWhites)){
            logger.debug("sequence:{}，ip在白名单内,授权通过,ip地址: {}", context.getMsgSeq(), ip);
            return;
        }else{
            logger.warn("sequence:{}，非白名单IP访问 ,来访ip地址: {}", context.getMsgSeq(), ip);
            throw new ApiBizException(ApiBizException.VERIFY_IP_ERROR, "用户不在白名单内,当前IP为: "+ip);
        }
    }

    private String getPartnerId(String reqXml) {
        if (StringUtils.isBlank(reqXml))
            return null;
        Matcher m = pattern.matcher(reqXml);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }

}

